package util.core;

import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;

public final class EditorDocumentUtils {

  public static void insertTextAtCaret(final Caret caret, final CharSequence text) {
    if (text == null) {
        return;
    }

    int textLength = text.length();
    int start;
    Document document = caret.getEditor().getDocument();
    if (caret.hasSelection()) {
      start = caret.getSelectionStart();
      int end = caret.getSelectionEnd();

      document.replaceString(start, end, text);
      caret.setSelection(start, start + textLength);
    } else {
      start = caret.getOffset();

      document.insertString(start, text);
    }
    caret.moveToOffset(start + textLength);
  }

  public static String getSelectionTextWithCaret(final Caret caret) {
      Document document = caret.getEditor().getDocument();
      int start;
      if (caret.hasSelection()) {
          start = caret.getSelectionStart();
          int end = caret.getSelectionEnd();

          return document.getText(new TextRange(start, end));
      }

      return null;
  }
}
